import {RequestHandler} from 'express-serve-static-core';
import fs from 'fs-extra';
import serverConstant from '../../configs/serverConstant';

const path_debugOperation_map = {
	'/show/me/the/waaagh': async (req, res, next) => {
		const {file = 'error', size = 1024 * 1024, sa} = req.query;
		if (file.includes('..')) return next();
		const logFile = `logs/${file}.log`;
		try {
			const stat = await fs.stat(logFile);
			const readStream = await fs.createReadStream(logFile, {start: Math.max(stat.size - size, 0), end: stat.size});
			res.type('html');
			res.write('<pre>');
			readStream.on('data', chunk => {
				res.write(chunk.toString().replace(/[<>]/g, char => (char === '<' ? '&lt;' : '&gt;')));
			});
			readStream.on('end', () => {
				res.write('</pre>');
				res.end();
			});
			readStream.on('error', () => {
				res.write('</pre>');
				res.end();
			});
		} catch (e) {
			console.error(e);
			res.end();
		}
	},
	'/cache/clean': async (req, res) => {
		const {path} = req.query;
		if (/^pages[/].*/.test(path) && !/[^a-zA-Z0-9./]|[./]{2,}/.test(path)) {
			console.warn('清除页面缓存:', path);
			await fs.remove(path);
			res.status(500).send('ojbk');
		} else {
			return res.status(404).end();
		}
	},
};

const debugInject: RequestHandler = async (req, res, next) => {
	const {ou} = req.query;
	if (serverConstant.prodMode && ou !== 'test') return next();
	const operation = path_debugOperation_map[req.path];
	if (operation) {
		operation(req, res, next);
	} else {
		next();
	}
};

export default debugInject;
